<?php
namespace App\Services;
use GeoIp2\Database\Reader;
use Exception,Log;
use GuzzleHttp\Client;

class IpService
{
    public static function getAddressByIp($ip)
    {
        try {
            $ipinfo = self::baiduMapIp($ip);
            if ($ipinfo["status"] == "success") {
                $province = $ipinfo["province"];
                $city = isset($ipinfo["city"]) ? $ipinfo["city"] : "";
            }
            if (is_array($province)) {
                $province = "";
                $city = "";
            } else {
                $province = mb_substr($province, 0, 10, 'utf-8');
                $city = mb_substr($city, 0, 10, 'utf-8');
            }
        } catch (Exception $e) {
            $province = "";
            $city = "";
        }
        return ["country"=>"","province"=>$province,"city"=>$city];
    }

    public static function baiduMapIp($ip)
    {
        try {          
            $client = new Client;
            $rand = rand(1,2);
            if ($rand == 1){
                // 腾讯300w/日
                $response = $client->request('GET', 'https://apis.map.qq.com/ws/location/v1/ip?key=DOXBZ-Q43CR-DWZW5-WQCDN-O6XPT-4BBE6&ip='.$ip);
                $body = $response->getBody();
                $ipdata = json_decode($body,true);
                if ($ipdata["status"] == 0) {
                    return ["status"=>"success","province"=>$ipdata["result"]["ad_info"]["province"],"city"=>$ipdata["result"]["ad_info"]["city"]];
                } else {
                    return ["status"=>"error","province"=>"未知","city"=>"未知"];
                }
            }else{
                // 免费300w/日，高德ip定位1.0
                $response = $client->request('GET', 'https://restapi.amap.com/v3/ip?key=a7eb8906de0eb0a04c09388df4a0708a&ip='.$ip,['timeout' => 1.5]);
                $body = $response->getBody();
                $ipdata = json_decode($body,true);
                if ($ipdata["status"] == 1) {
                    $province = empty($ipdata["province"]) ? "未知" : $ipdata["province"];
                    $city = empty($ipdata["city"]) ? "未知" : $ipdata["city"];
                    return ["status"=>"success","province"=>$province,"city"=>$city];
                } else {
                    return ["status"=>"error","province"=>"未知","city"=>"未知"];
                }
            }
        } catch (Exception $e) {
            return ["status"=>"error","province"=>"未知","city"=>"未知"];
        }
    }
}
